<template>
  <view class="tn-shop-order-detail">
    <tn-custom :is-alpha="true">
      <block slot="left">
        <view class='action border-custom text-white bg-top-home' :style="'width:' + Custom.width + 'px;height:' + Custom.height + 'px;margin-left:calc(750rpx - ' + Custom.right + 'px)'"
          @click="goBack">
          <text class='cuIcon-back'></text>
          <text class='cuIcon-homefill'></text>
        </view>
      </block>
    </tn-custom>
    
    <block v-if="orderData && orderData.order_no != ''">
      <view class="flex justify-between align-center order-base-info" :style="[{paddingTop: CustomBar + 'px', height: (CustomBar + 140) + 'px'}]">
        <view class="content">
          <view class="tips">
            <text v-if="[1,2,5,9,10,14].indexOf(orderData.status) != -1" class="icon cuIcon-time"></text>
            <text class="title text-blod">{{ orderStatusValue }}</text>
            <!-- <text v-if="orderData.status == 2" class="title text-blod">等待发货</text>
            <text v-if="orderData.status == 3" class="title text-blod">支付失败</text>
            <text v-if="orderData.status == 4" class="title text-blod">订单关闭</text>
            <text v-if="orderData.status == 5" class="title text-blod">等待退款到账</text>
            <text v-if="orderData.status == 6" class="title text-blod">退款完成</text>
            <text v-if="orderData.status == 7" class="title text-blod">退款异常</text>
            <text v-if="orderData.status == 8" class="title text-blod">退款关闭</text>
            <text v-if="orderData.status == 9" class="title text-blod">等待收货</text>
            <text v-if="orderData.status == 10" class="title text-blod">等待退款申请通过</text>
            <text v-if="orderData.status == 11" class="title text-blod">交易完成</text>
            <text v-if="orderData.status == 12" class="title text-blod">支付超时</text> -->
          </view>
          <view class="time-content">
            <view v-if="orderData.status == 1" class="time-content-tips">
              <text class="time-content-tips-title">需付款：</text><text class="price-unit">¥</text><text class="price-integer">{{ orderData.amount | priceInteger}}</text><text class="price-decimal">.{{ orderData.amount | priceDecimal}}</text>
            </view>
            <view v-if="orderData.virtual_product == 0 && orderData.status == 2" class="time-content-tips">
              请耐心等待卖家发货
            </view>
            <view v-if="orderData.virtual_product == 1 && orderData.status == 2" class="time-content-tips">
              请耐心等待卖家进行服务
            </view>
            <view v-if="orderData.virtual_product == 1 && orderData.status == 9" class="time-content-tips">
              请耐心等待快递小哥哥把货物送到府上
            </view>
            <view v-if="orderData.status == 10" class="time-content-tips">
              {{ orderData.user_application_refund_reason }}
            </view>
            <view v-if="orderData.status == 1" class="time-content-time">
              <text class="time-content-time-title">剩余：</text><text class="min">{{ countDownTime.min | fillTimeFormat }}分</text><text class="sec">{{ countDownTime.sec | fillTimeFormat }}秒</text>
            </view>
            <view v-if="[9,14].indexOf(orderData.status) != -1" class="time-content-time">
              <text class="time-content-time-title">剩余：</text><text class="day">{{ countDownTime.day | fillTimeFormat }}天</text><text class="hour">{{ countDownTime.hour | fillTimeFormat }}小时</text>
            </view>
            <view v-if="orderData.status == 10" class="time-content-time">
              <text class="time-content-time-title">剩余：</text><text class="day">{{ countDownTime.day | fillTimeFormat }}天</text><text class="hour">{{ countDownTime.hour | fillTimeFormat }}小时</text>
            </view>
          </view>
        </view>
        <view class="image">
          <!-- 等待支付 -->
          <image v-if="orderData.status == 1" src="../static/images/wait_pay.png" mode="aspectFit" ></image>
          <!-- 等待发货 -->
          <image v-if="orderData.status == 2" src="../static/images/wait_delivery.png" mode="aspectFit" ></image>
          <!-- 订单关闭 -->
          <image v-if="orderData.status == 4" src="../static/images/close_order.png" mode="aspectFit" ></image>
          <!-- 等待收货 -->
          <image v-if="[9,14].indexOf(orderData.status) != -1" src="../static/images/wait_receipts.png" mode="aspectFit" ></image>
          <!-- 等待退款申请 -->
          <image v-if="orderData.status == 10" src="../static/images/application_refund.png" mode="aspectFit" ></image>
          <!-- 订单结束 -->
          <image v-if="[3,5,6,7,8,11,12,13].indexOf(orderData.status) != -1" src="../static/images/end_order.png" mode="aspectFit" ></image>
        </view>
      </view>
      
      <view class="order-detail" :style="[{paddingTop: (CustomBar + 140) + 'px'}]">
        
        <tn-show-product-info
          :product-data="orderData.product"
        >
        </tn-show-product-info>
        
        <view class="cu-card case product-list">
          <view class="cu-item order-price">
            <view class="flex justify-between align-center text-gray sum-price">
              <view class="order-price-title">
                商品总价
              </view>
              <view class="order-price-value">
                <text class="price-unit">¥</text><text class="price-integer">{{ orderData.amount | priceInteger}}</text><text class="price-decimal">.{{ orderData.amount | priceDecimal}}</text>
              </view>
            </view>
            <view class="flex justify-between align-center text-gray deliver-price">
              <view class="order-price-title">
                运费(快递)
              </view>
              <view class="order-price-value">
                <text class="price-unit">¥</text><text class="price-integer">{{ orderData.freight | priceInteger}}</text><text class="price-decimal">.{{ orderData.freight | priceDecimal}}</text>
              </view>
            </view>
            <view class="flex justify-between align-center text-black preferential-price">
              <view class="order-price-title">
                优惠价格
              </view>
              <view class="order-price-value">
                <text class="price-unit">-¥</text><text class="price-integer">{{ 0.00 | priceInteger}}</text><text class="price-decimal">.{{ 0.00 | priceDecimal}}</text>
              </view>
            </view>
            <view class="flex justify-between align-center text-black amount-price">
              <view class="order-price-title">
                实付款
              </view>
              <view class="order-price-value">
                <text class="price-unit">¥</text><text class="price-integer">{{ orderData.amount | priceInteger}}</text><text class="price-decimal">.{{ orderData.amount | priceDecimal}}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="cu-list menu tn-border address">
          <view class="cu-item">
            <view class="">
              <text class="">收货人</text>
            </view>
            <view class="">
              <view class="">{{ orderData.address.user_name }}</view>
            </view>
          </view>
          <view class="cu-item">
            <view class="">
              <text class="">联系方式</text>
            </view>
            <view class="">
              <view class="">{{ orderData.address.tel_number }}</view>
            </view>
          </view>
          <view class="cu-item">
            <view style="width: 200rpx;">
              <text class="">收货地址</text>
            </view>
            <view class="">
              <view class="tn-align">
                {{ orderData.address.province_name }}
                {{ orderData.address.city_name }}
                {{ orderData.address.county_name }}
                {{ orderData.address.detail_info }}
              </view>
            </view>
          </view>
        </view>
        
        <view class="cu-list menu tn-border express">
          <block v-if="orderData.express.logistics_information.length == 0">
            <view class="flex align-center justify-center express-info">
              暂无物流信息
            </view>
          </block>
          
          <block v-else>
            <view class="flex align-center express-info" @click="copyExpressOrderNo">
              <text class="express-info-company-name">
                {{ orderData.express.express_company.name }}
              </text>
              <text class="express-info-order-no">
                {{ orderData.express.express_no }}<text class="cuIcon cuIcon-copy" style="margin-left: 5px;"></text>
              </text>
            </view>
            <view class="" :class="[showMoreExpressInfoFlag ? '' : 'express-time-info-hide']" :animation="showMoreExpressAnimationData">
              <view id="express-info-timeline">
                <view v-for="(express_info_item, express_info_index) in orderData.express.logistics_information" :key="express_info_index" class="flex justify-between express-timeline">
                	<view class="express-time">
                    <view>{{ express_info_item.ftime | getExpressDateMonth }}</view>
                    <view>{{ express_info_item.ftime | getExpressDateHours }}</view>
                  </view>
                	<view class="express-content">
                		<view class="content">
                			{{ express_info_item.context }}
                		</view>
                	</view>
                </view>
                <!-- <view class="flex justify-between express-timeline">
                	<view class="express-time">06-17 21:24</view>
                	<view class="express-content">
                		<view class="content">
                			<text>01:30</text> 【喵星】 MX-12138 已揽收，准备发往银河系
                		</view>
                	</view>
                </view>
                <view class="flex justify-between express-timeline">
                	<view class="express-time">06-17 21:24</view>
                	<view class="express-content">
                		<view class="content">
                			<text>01:30</text> 【喵星】 MX-12138 已揽收，准备发往银河系
                		</view>
                	</view>
                </view> -->
              </view>
              <view class="flex align-end justify-center express-time-info-show-more" :class="[showMoreExpressInfoFlag ? 'express-time-info-show-more-hide' : '']" @click="showMoreExpressInfo">
                <text class="text">
                  点击查看更多物流信息<text class="cuIcon cuIcon-rounddown" style="margin-left: 8px;"></text>
                </text>
              </view>
            </view>
          </block>
        </view>
        
        <view class="cu-list menu tn-border order-information">
          <view class="cu-item">
            <view class="">
              <text class="">订单编号</text>
            </view>
            <view class="action">
              <view class="">{{ orderData.order_no }}</view>
            </view>
          </view>
          <view v-if="orderData.transaction_id && orderData.transaction_id != ''" class="cu-item">
            <view class="">
              <text class="">微信支付交易号</text>
            </view>
            <view class="action">
              <view class="">{{ orderData.transaction_id }}</view>
            </view>
          </view>
          <view v-if="orderData.user_application_refund_reason && orderData.user_application_refund_reason != ''" class="cu-item">
            <view class="">
              <text class="">退款理由</text>
            </view>
            <view class="">
              <view class="">{{ orderData.user_application_refund_reason }}</view>
            </view>
          </view>
          <view class="cu-item">
            <view class="">
              <text class="">下单时间</text>
            </view>
            <view class="">
              <view class="">{{ orderData.create_time }}</view>
            </view>
          </view>
          <view v-if="orderData.pay_time && orderData.pay_time != ''" class="cu-item">
            <view class="">
              <text class="">付款时间</text>
            </view>
            <view class="">
              <view class="">{{ orderData.pay_time }}</view>
            </view>
          </view>
          <view v-if="orderData.delivery_time && orderData.delivery_time != ''" class="cu-item">
            <view class="">
              <text class="">发货时间</text>
            </view>
            <view class="">
              <view class="">{{ orderData.delivery_time }}</view>
            </view>
          </view>
          <view v-if="orderData.user_application_time && orderData.user_application_time != ''" class="cu-item">
            <view class="">
              <text class="">退款申请时间</text>
            </view>
            <view class="">
              <view class="">{{ orderData.user_application_time }}</view>
            </view>
          </view>
          <view v-if="orderData.refund_create_time && orderData.refund_create_time != ''" class="cu-item">
            <view class="">
              <text class="">退款处理时间</text>
            </view>
            <view class="">
              <view class="">{{ orderData.refund_create_time }}</view>
            </view>
          </view>
          <view v-if="orderData.order_end_time && orderData.order_end_time != ''" class="cu-item">
            <view class="">
              <text class="">完成时间</text>
            </view>
            <view class="">
              <view class="">{{ orderData.order_end_time }}</view>
            </view>
          </view>
        </view>
        
      </view>
    </block>
    
    <view class="cu-tabbar-height"></view>

    <view class="cu-bar bg-white tabbar border shop tn-footerfixed">
      <button class="action text-gray" open-type="contact">
        <view class="cuIcon-service">
        </view> 客服
      </button>
      <view class="operation">
        <view class="btn">
          <button
            v-if="orderData.virtual_product == 1 && orderData.status == 2"
            class="cu-btn line-gray round shadow-blur"
            open-type="contact"
            :show-message-card="true"
            :send-message-title="orderData.product[0].product_title + '购买后服务'"
            :send-message-img="orderData.product[0].product_image.prefix"
            :send-message-path="'/tn_shop/product_detail/product_detail?id=' + orderData.product[0].specs_id"
            @tap.native.stop=""
          >
            联系客服
          </button>
          <button v-if="[4,11,12].indexOf(orderData.status) != -1" class="cu-btn bg-gray round shadow-blur" @click="deleteOrder">删除订单</button>
          <button v-if="orderData.status == 1" class="cu-btn bg-gray round shadow-blur" @click="closeOrder">关闭订单</button>
          <button v-if="[9,14].indexOf(orderData.status) != -1" class="cu-btn bg-gray round shadow-blur" @click="confirmReceiptOrder">确认收货</button>
          <button v-if="[2,7,11].indexOf(orderData.status) != -1" class="cu-btn bg-gray round shadow-blur" @click="openLaunchRefundModal">申请退款</button>
          <button v-if="orderData.status == 10" class="cu-btn bg-gray round shadow-blur" @click="closeRefundApplication">取消退款</button>
          <button v-if="orderData.status == 1" class="cu-btn bg-gray round shadow-blur" @click="payOrder">立即付款</button>
        </view>
      </view>
    </view>
    
    <view v-if="showLaunchRefundModal" class="cu-modal" :class="showLaunchRefundModal?'show':''">
    	<view class="cu-dialog">
    		<view class="cu-bar bg-white justify-end">
    			<view class="content">申请退款</view>
    			<view class="action" @click="closeLaunchRefundModal">
    				<text class="cuIcon-close text-red"></text>
    			</view>
    		</view>
    		<view class="">
          <form>
            <view class="cu-form-group align-start">
            	<view class="title">退款原因</view>
            	<textarea maxlength="255" v-model="launchApplicationReason" placeholder="请输入退款原因"></textarea>
            </view>
          </form>
    		</view>
    		<view class="cu-bar bg-white justify-end">
    			<view class="action">
    				<button class="cu-btn line-green text-green" @click="closeLaunchRefundModal">取消</button>
    				<button class="cu-btn bg-green margin-left" @click="applicationRefund">确定</button>
    
    			</view>
    		</view>
    	</view>
    </view>
    
    <tn-wx-login :show="showLogin" desc="用户记录您的登录信息" @closeLoginModal="closeLoginModal" @getUserInfo="getUserInfo"></tn-wx-login>
    
  </view>
</template>

<script>
  import TnShowProductInfo from '../components/tn-show-product-info/tn-show-product-info'
  import {
    checkUserScope,
    getUserInfo
  } from '@/utils/user.js'
  import {
    getTNShopOrderByID,
    closeTNShopOrder,
    deleteTNShopOrder,
    confirmReceiptTNShopOrder,
    launchOrderRefundTNShopOrder,
    closeTNShopRefundApplication,
    setTNShopAllowDeliverySubscribe
  } from '@/api/tn-shop-order.js'
  import {
    payTNShopOrder
  } from '@/api/pay.js'
  
  const util = require('@/utils/util')
  let countDownTimer = null
  
  export default {
    name: 'TnShopOrderDetail',
    components: { TnShowProductInfo },
    data() {
      return {
        Custom: this.Custom,
        CustomBar: this.CustomBar,
        from: '',                         // 标记用户从那个页面过来订单详情
        id: 0,                            // 订单id
        orderData: {
          virtual_product: 0,
          freight: 0.00,
          order_no: '',
          transaction_id: '',
          amount: 0.00,
          product: [],
          address: {
            user_name: '',
            tel_number: '',
            province_name: '',
            city_name: '',
            county_name: '',
            detail_info: ''
          },
          express: {
            express_company: {
              name: ''
            },
            express_no: '',
            logistics_information: []
          }
        },                                // 订单详情信息
        countDownTime: {
          endTime: 0,
          day: 0,
          hour: 0,
          min: 0,
          sec: 0
        },                                // 保存倒计时时间数据
        orderStatusTitle: [
          { status: 1, title: '等待付款'},
          { status: 2, title: '等待发货'},
          { status: 3, title: '支付失败'},
          { status: 4, title: '订单关闭'},
          { status: 5, title: '等待退款到账'},
          { status: 6, title: '退款完成'},
          { status: 7, title: '退款异常'},
          { status: 8, title: '退款关闭'},
          { status: 9, title: '等待收货'},
          { status: 10, title: '等待退款申请通过'},
          { status: 11, title: '交易完成'},
          { status: 12, title: '支付超时'},
          { status: 13, title: '用户取消退款申请'},
          { status: 14, title: '等待确认收货'},
        ],                                // 订单状态标题
        virtualProductOrderStatusTitle: [
          { status: 1, title: '等待付款'},
          { status: 2, title: '联系卖家进行服务'},
          { status: 3, title: '支付失败'},
          { status: 4, title: '订单关闭'},
          { status: 5, title: '等待退款到账'},
          { status: 6, title: '退款完成'},
          { status: 7, title: '退款异常'},
          { status: 8, title: '退款关闭'},
          { status: 9, title: '等待确认服务完成'},
          { status: 10, title: '等待退款申请通过'},
          { status: 11, title: '交易完成'},
          { status: 12, title: '支付超时'},
          { status: 13, title: '用户取消退款申请'},
          { status: 14, title: '等待确认服务完成'},
        ],                                // 服务商品订单状态标题
        showMoreExpressInfoFlag: false,   // 是否显示更多的物流信息
        showMoreExpressAnimationData: {}, // 显示更多物流信息展示动画
        showLaunchRefundModal: false,     // 是否显示申请退款信息填写窗口
        launchApplicationReason: '',      // 用户申请退款原因
        checkUserScopeFlag: false,        //用户是否已经授权
        showLogin: false,                 //打开登陆框
      };
    },
    onLoad(options) {
      this.from = options.from || ''
      this.id = options.id || 0
      
      this._loadData()
    },
    onUnload() {
      if (countDownTimer) {
        clearInterval(countDownTimer)
      }
    },
    computed: {
      // 获取当前状态对应的标题
      orderStatusValue: function () {
        let status_value = ''
        if (this.orderData.virtual_product == 1) {
          status_value = this.virtualProductOrderStatusTitle.filter((item) => {
            return item.status == this.orderData.status
          })
        } else {
          status_value = this.orderStatusTitle.filter((item) => {
            return item.status == this.orderData.status
          })
        }
        // console.log(status_value);
        return status_value.length > 0 ? status_value[0].title : ''
      }
    },
    filters: {
      // 金额显示过滤器(取出整数)
      priceInteger(n = 0.00) {
        if (typeof n == "string") {
          n = parseFloat(n)
        }
        n = n.toFixed(2)
        n = n.toString()
        return n.split(".")[0]
      },
      // 金额显示过滤器(取出小数)
      priceDecimal(n = 0.00) {
        if (typeof n == "string") {
          n = parseFloat(n)
        }
        n = n.toFixed(2)
        n = n.toString()
        return n.split(".")[1]
      },
      // 对时间进行格式填充
      fillTimeFormat(time) {
        if (time < 10) {
          return '0' + time
        }
        return time
      },
      // 格式化物流时间（取出月日）
      getExpressDateMonth(ftime) {
        const time = new Date(ftime)
        return (time.getMonth() + 1) + '-' + time.getDate()
      },
      // 格式化物流时间（取出时分）
      getExpressDateHours(ftime) {
        const time = new Date(ftime)
        return (time.getHours()) + ':' + time.getMinutes()
      }
    },
    methods: {
      
      // 删除订单
      deleteOrder() {
        this._showConfirmModal('操作订单提醒', '确定需要删除订单吗?', () => {
          deleteTNShopOrder({
            id: this.id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshOrderData()
            })
          }).catch(() => {
            this._showOperationOrderTips('删除订单失败')
          })
        })
      },
      
      // 关闭订单
      closeOrder() {
        this._showConfirmModal('操作订单提醒', '确定需要关闭订单吗?', () => {
          closeTNShopOrder({
            id: this.id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshOrderData()
            })
          }).catch(() => {
            this._showOperationOrderTips('关闭订单失败')
          })
        })
      },
      
      // 确认收货
      confirmReceiptOrder() {
        this._showConfirmModal('操作订单提醒', '确定已经收到货物了吗?', () => {
          confirmReceiptTNShopOrder({
            id: this.id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshOrderData()
            })
          }).catch(() => {
            this._showOperationOrderTips('订单确认收货失败')
          })
        })
      },
      
      // 对订单进行支付操作
      payOrder() {
        payTNShopOrder({
          id: this.id
        }).then((response) => {
          const { data } = response
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: (res) => {
              this._checkDeliverySubscribe(data.order_no, () => {
                setTimeout(() => {
                  if(this.orderData.virtual_product) {
                    uni.showModal({
                      showCancel:false,
                      title: "购买提示",
                      content: "当前购买的是服务商品，请购买后点击联系客服进行服务",
                      success: (res) => {
                        if(res.confirm) {
                          this._refreshOrderData()
                        }
                      }
                    })
                  } else {
                    this._refreshOrderData()
                  }
                }, 1500)
              })
              uni.showToast({
                title: '支付成功...',
                icon: 'none'
              })
            },
            fail: async (err) => {
              uni.showToast({
                title: '支付失败',
                icon: 'none'
              })
            }
          })
        })
      },
      
      // 打开申请退款信息填写窗口
      openLaunchRefundModal() {
        this.showLaunchRefundModal = true
      },
      
      // 关闭申请退款信息填写窗口
      closeLaunchRefundModal() {
        this.showLaunchRefundModal = false
        this.launchApplicationReason = ''
      },
      
      // 申请退款
      async applicationRefund() {
        const allow_ids = await util.checkSubscribeSetting(['PDkrF01llNsWjEQpCNwaYXsIvDEjlttRQCLWmwFR7Mk'])
        
        const allow_refund_subscribe = allow_ids.indexOf('PDkrF01llNsWjEQpCNwaYXsIvDEjlttRQCLWmwFR7Mk') != -1 ? 1 : 0
        
        launchOrderRefundTNShopOrder({
          id: this.id,
          refund_reason: this.launchApplicationReason,
          allow_refund_subscribe
        }).then((response) => {
          const { msg } = response
          this._showOperationOrderTips(msg, () => {
            this._refreshOrderData()
          })
        }).catch(() => {
          this._showOperationOrderTips('申请退款失败')
        })
      },
      
      // 用户取消退款
      closeRefundApplication() {
        this._showConfirmModal('操作订单提醒', '确定取消退款吗？', () => {
          closeTNShopRefundApplication({
            id: this.id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshOrderData()
            })
          }).catch(() => {
            this._showOperationOrderTips('订单取消退款失败')
          })
        })
      },
      
      // 显示更多的物流信息
      showMoreExpressInfo() {
        // 获取物流信息的高度信息
        let express_timeline_height = 0
        const express_timeline_query = uni.createSelectorQuery().in(this)
        express_timeline_query.select('#express-info-timeline').boundingClientRect((data) => {
          // console.log(data);
          express_timeline_height = data.height
          this.showMoreExpressInfoFlag = true
          let animation = uni.createAnimation({
            duration: 700,
            timingFunction: 'ease'
          })
          animation.height(express_timeline_height).step()
          this.showMoreExpressAnimationData = animation.export()
        }).exec()
      },
      
      // 复制物流单号
      copyExpressOrderNo() {
        uni.setClipboardData({
          data: this.orderData.express.express_no || '',
          success: () => {
            uni.showToast({
              icon: 'success',
              title: '复制成功'
            })
          }
        })
      },
      
      //获取用户登陆状态
      getUserInfo() {
        if (res != null) {
          updateUserInfoToServer(res).then(() => {
            this.checkUserScopeFlag = true;
            util.showTips('登陆成功', '请继续执行上一步操作');
            this.closeLoginModal()
          }).catch(() => {
            util.showTips('授权提示', '获取授权失败')
            this.closeLoginModal()
          })
        } else {
          this.closeLoginModal()
        }
      },
      
      // 跳转回指定页面
      goBack() {
        uni.navigateBack({
          delta: 1
        })
      },
      
      // 关闭登录窗口
      closeLoginModal() {
        // console.log('close Login');
        this.showLogin = false
      
      },
      
      // 加载数据
      _loadData() {
        this._checkUserScope().then(() => {
          this._getOrderDetailData()
        }).catch(() => {
          // 如果用户还没有登录授权，直接返回
          this.goBack()
        })
      },
      
      // 刷新订单详情数据
      _refreshOrderData() {
        // 如果有定时器正在执行，则先停止
        if (countDownTimer) {
          clearInterval(countDownTimer)
        }
        
        // 清空退款申请信息
        this.showLaunchRefundModal = false
        this.launchApplicationReason = ''
        this._refreshOrderList()
        this._getOrderDetailData()
      },
      
      // 发送刷新订单列表的信号
      _refreshOrderList() {
        uni.$emit("refresh_order_list", null)
      },
      
      // 根据id获取订单的详情数据
      _getOrderDetailData() {
        uni.showLoading({
          title: '加载中...'
        })
        getTNShopOrderByID({
          id: this.id
        }).then((response) => {
          uni.hideLoading()
          const { data } = response
          // 判断是否为服务商品订单
          const have_virtual_product = data.product.some((product_item) => {
            return product_item.virtual_product == 1
          })
          this.orderData = {
            virtual_product: have_virtual_product,
            address: data.address,
            amount: data.amount,
            create_time: data.create_time || '',
            create_time_stamp: data.create_time_stamp || 0,
            delivery_time: data.delivery_time || '',
            delivery_time_stamp: data.delivery_time_stamp || 0,
            express: data.express || { logistics_information: [] },
            freight: data.freight || 0.00,
            order_end_time: data.order_end_time || '',
            order_no: data.order_no || '',
            pay_time: data.pay_time || '',
            product: data.product || [],
            refund_create_time: data.refund_create_time || '',
            status: data.status || 0,
            transaction_id: data.transaction_id || '',
            user_application_refund_reason: data.user_application_refund_reason || '',
            user_application_refund_time: data.user_application_refund_time || '',
            user_application_refund_time_stamp: data.user_application_refund_time_stamp || 0
          }
          this._createCountDownTime()
        }).catch((err) => {
          console.log(err);
          this._showOperationOrderTips('请重新选择订单', () => {
            this.goBack()
          })
        })
      },
      
      // 创建倒计时(待付款，待收货)
      _createCountDownTime() {
        // 判断状态是待付款还是待收货
        if (this.orderData.status == 1) {
          this.countDownTime.endTime = ((this.orderData.create_time_stamp ) + (30 * 60)) * 1000
          const now_stamp = (this.countDownTime.endTime - Date.parse(new Date())) / 1000
          this.countDownTime.min = parseInt(now_stamp  / 60 % 60, 10);//计算剩余的分钟数
          this.countDownTime.sec = parseInt(now_stamp  % 60, 10);//计算剩余的秒数
          countDownTimer = setInterval(() => {
            const now_stamp = (this.countDownTime.endTime - Date.parse(new Date())) / 1000
            // console.log(this.countDownTime.endTime, Date.parse(new Date()), now_stamp);
            // const day = parseInt(now_stamp  / 60 / 60 / 24, 10);//计算剩余的天数
            // const hour = parseInt(now_stamp  / 60 / 60 % 24, 10);//计算剩余的小时数
            this.countDownTime.min = parseInt(now_stamp  / 60 % 60, 10);//计算剩余的分钟数
            this.countDownTime.sec = parseInt(now_stamp  % 60, 10);//计算剩余的秒数
          }, 1000)
        }
        
        if ([9,14].indexOf(this.orderData.status) != -1) {
          // let sign_time = 0
          // if (this.orderData.virtual_product == 1) {
          //   sign_time = this.orderData.delivery_time_stamp * 1000
          // } else {
          //   sign_time = new Date(this.orderData.express.logistics_information[0].ftime).getTime()
          // }
          // this.countDownTime.endTime = ((sign_time / 1000) + (14 * 24 * 60 * 60)) * 1000
          this.countDownTime.endTime = (this.orderData.delivery_time_stamp + (14 * 24 * 60 * 60)) * 1000
          // console.log(this.countDownTime.endTime);
          const now_stamp = (this.countDownTime.endTime - Date.parse(new Date())) / 1000
          this.countDownTime.day = parseInt(now_stamp  / 60 / 60 / 24, 10);//计算剩余的天数
          this.countDownTime.hour = parseInt(now_stamp  / 60 / 60 % 24, 10);//计算剩余的小时数
          countDownTimer = setInterval(() => {
            const now_stamp = (this.countDownTime.endTime - Date.parse(new Date())) / 1000
            this.countDownTime.day = parseInt(now_stamp  / 60 / 60 / 24, 10);//计算剩余的天数
            this.countDownTime.hour = parseInt(now_stamp  / 60 / 60 % 24, 10);//计算剩余的小时数
            // this.countDownTime.min = parseInt(now_stamp  / 60 % 60, 10);//计算剩余的分钟数
            // this.countDownTime.sec = parseInt(now_stamp  % 60, 10);//计算剩余的秒数
          }, 1000 * 60 * 60)
        }
        
        if (this.orderData.status == 10) {
          this.countDownTime.endTime = ((this.orderData.user_application_refund_time_stamp ) + (3 * 24 * 60 * 60)) * 1000
          const now_stamp = (this.countDownTime.endTime - Date.parse(new Date())) / 1000
          this.countDownTime.day = parseInt(now_stamp  / 60 / 60 / 24, 10);//计算剩余的天数
          this.countDownTime.hour = parseInt(now_stamp  / 60 / 60 % 24, 10);//计算剩余的小时数
          countDownTimer = setInterval(() => {
            const now_stamp = (this.countDownTime.endTime - Date.parse(new Date())) / 1000
            this.countDownTime.day = parseInt(now_stamp  / 60 / 60 / 24, 10);//计算剩余的天数
            this.countDownTime.hour = parseInt(now_stamp  / 60 / 60 % 24, 10);//计算剩余的小时数
            // this.countDownTime.min = parseInt(now_stamp  / 60 % 60, 10);//计算剩余的分钟数
            // this.countDownTime.sec = parseInt(now_stamp  % 60, 10);//计算剩余的秒数
          }, 1000 * 60 * 60)
        }
      },
      
      // 如果支付成功询问用户是否推送发货通知
      async _checkDeliverySubscribe(order_no, success_function) {
        const allow_ids = await util.checkSubscribeSetting(['9hwrLTmuWYtknZO6d5zog8pkt_Noi-Fp0cEHkaydipc'])
        
        if (allow_ids.indexOf('9hwrLTmuWYtknZO6d5zog8pkt_Noi-Fp0cEHkaydipc') != -1) {
          setTNShopAllowDeliverySubscribe({
            order_no,
            allow_delivery_subscribe: 1
          }).then(() => {
            if (success_function && typeof(success_function) === 'function') {
              success_function()
            }
          })
        } else {
          if (success_function && typeof(success_function) === 'function') {
            success_function()
          }
        }
      },
      
      // 显示订单操作确认提示框
      _showConfirmModal(title = '', content = '', success_function) {
        uni.showModal({
          title,
          content,
          success: (res) => {
            if (res.confirm) {
              if (success_function && typeof(success_function) === 'function') {
                success_function()
              }
            }
          }
        })
      },
      
      // 订单操作信息提示框
      _showOperationOrderTips(title = '', end_function) {
        uni.showToast({
          icon: 'none',
          title,
          success: () => {
            setTimeout(() => {
              if (end_function && typeof(end_function) === 'function') {
                end_function()
              }
            }, 1500)
          }
        })
      },
      
      // 
      
      /**
       * 检查当前用户的权限
       */
      _checkUserScope() {
        return new Promise((resolve, reject) => {
          checkUserScope().then((res) => {
            this.checkUserScopeFlag = res
            resolve();
          }).catch((res) => {
            this.checkUserScopeFlag = res
            reject();
          });
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
.tn-shop-order-detail {
  // background-color: #f1eef3;
  // margin: 0;
  // width: 100%; 
  // height: 100vh; 
  // background: linear-gradient(45deg,#F15BB5, #9A5CE5, #01BEFF,#00F5D4); 
  // background-size: 500% 500%; 
  // animation: gradientBG 15s ease infinite; 
  
  .order-base-info {
    margin: 0;
    width: 100%; 
    // height: 100vh; 
    background: linear-gradient(45deg,#F15BB5, #9A5CE5, #01BEFF,#00F5D4); 
    background-size: 500% 500%; 
    animation: gradientBG 15s ease infinite; 
    color: #fff; 
    // color: #000000;
    
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    
    .content {
      margin-left: 40px;
      
      .tips {
        font-size: 30rpx;
        
        .title {
          margin-left: 5px;
        }
      }
      
      .time-content {
        font-size: 20rpx;
      }
    }
    
    .image  {
      width: 40%;
      margin-right: 20px;
      image {
        height: 100px;
      }
    }
  }
  
  .order-detail {
    background-color: #FFFFFF;
    // border-radius: 15px 15px 0px 0px;
    
    .order-price {
      .sum-price, .deliver-price, .preferential-price {
        font-size: 12px;
        .price-unit {
          letter-spacing: 2px;
          font-size: 10px;
        }
        
        .price-integer {
          font-size: 14px;
        }
        
        .price-decimal {
          font-size: 10px;
        }
      }
      .preferential-price {
        margin-top: 5px;
      }
    }
  }
  
  .express {
    background-color: #ffffff;
    .express-info {
      height: 68rpx;
      background-color: #e2e2e2;
      .express-info-company-name {
        margin-left: 30rpx;
      }
      .express-info-order-no {
        margin-left: 10rpx;
      }
    }
    .express-timeline {
      .express-time {
        width: 120rpx;
        text-align: center;
        padding: 45rpx 0;
        font-size: 26rpx;
        color: #888;
        display: block;
      }
      .express-content {
        color: #ccc;
        padding: 30rpx 30rpx 30rpx 45rpx;
        position: relative;
        display: block;
        z-index: 0;
        width: 735rpx;
        .content {
          background-color: #f1f1f1;
          color: #333333;
          padding: 30rpx;
          border-radius: 6rpx;
          display: block;
          line-height: 1.6;
        }
        &:before {
          content: "\e763";
          font-family: "cuIcon";
          display: block;
          position: absolute;
          top: 36rpx;
          z-index: 9;
          background-color: #ffffff;
          width: 50rpx;
          height: 50rpx;
          text-align: center;
          border: none;
          line-height: 50rpx;
          left: -11rpx;
        }
        &:after {
          content: "";
          display: block;
          position: absolute;
          width: 1rpx;
          background-color: #ddd;
          left: 13rpx;
          height: 100%;
          top: 0;
          z-index: 8;
        }
      }
      
      &:first-child .express-content::after {
        top: 40rpx;
      }
      &:last-child .express-content::after {
        height: 50rpx;
      }
    }
    
    .express-time-info-hide {
      height: 240rpx;
      position: relative;
    }
    
    .express-time-info {
      height: auto;
      // animation: show-more-express-frames 0.7s ease;
    }
    
    .express-time-info-show-more {
      width: 100%;
      height: 100%;
      background: linear-gradient(rgba(0, 0, 0, 0.01), rgba(0, 0, 0, 0.7));
      position: absolute;
      bottom: 0;
      .text {
        margin-bottom: 15rpx;
        font-size: 30rpx;
        color: #FFFFFF;
      }
    }
    
    .express-time-info-show-more-hide {
      display: none;
    }
  }
  
  .operation {
    margin-right: 25rpx;
  
    .btn button {
      margin-left: 10px;
      background-color: #f0f0f0;
      color: #333333;
      line-height: 45rpx;
      font-size: 25rpx;
      height: 50rpx;
    }
  
    .btn button:last-child {
      background-color: #e54d42;
      color: #FFFFFF;
    }
  }
  
  .order-information {
    margin-top: 0px;
  }
  
  .price-title {
    letter-spacing: 2px;
    font-size: 16px;
  }
  
  .price-unit {
    letter-spacing: 2px;
    font-size: 12px;
  }
  
  .price-integer {
    font-size: 16px;
  }
  
  .price-decimal {
    font-size: 12px;
  }
}

@keyframes show-more-express-frames {
  0% {
    opacity: 0.3;
    
  }
  100% {
    opacity: 1;
  }
}
@keyframes gradientBG { 
    0% { 
        background-position: 0% 50%; 
    } 
    50% { 
        background-position: 100% 50%; 
    } 
    100% { 
        background-position: 0% 50%; 
    } 
}
</style>
